package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * @param dto 前端请求数据
     * @return 登录结果
     * @Description 自媒体登录
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.校验参数：用户名和密码不能null
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码错误");
        }
        //2 查询自媒体用户是否存在
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName, dto.getName())
                .eq(WmUser::getStatus, AdminConstants.PASS_AUTH));
        if (ObjectUtils.isEmpty(wmUser)) {
            CustomException.custom(AppHttpCodeEnum.DATA_NOT_EXIST, "该用户不存在！");
        }
        //3. 对比密码
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (!wmUser.getPassword().equals(pwd)) {
            CustomException.custom(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4 返回token和用户id集合对象
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user", wmUser);
        return ResponseResult.okResult(map);
    }
}
